<?php
/**
 * 检测算力套餐是否已到期，到期的退还本金到usdt钱包(credit2).
 * User: admin
 * Date: 2019/10/8
 * Time: 18:34
 */
if (!defined("APP_PATH")) {
    define('APP_PATH', __DIR__ . '/application/');
    // 加载框架引导文件
    require __DIR__ . '/thinkphp/start.php';
}

echo '开始执行时间：'.date('Y-m-d H:i:s')."\r\n";
//今天的开始时间
$stime = strtotime(date('Y-m-d'));
//今天的结束时间
//$etime = strtotime(date('Y-m-d 23:59:59'));
//首先拿1000条到期的数据
$data = db('tc_order')->where('duetime','<=',time())->where('status',0)->where('days_d',0)->field('id,uid,username,tcid,price_d')->limit(0,1000)->select();
//获取所有等级的算力套餐信息
$tcinfo = db('tc_manage')->where('id','>',0)->column('id,level,per,name_cn,name_en','id');

//获取表前缀
$prefix = config('database.prefix');
$db = new \think\Db();
while($data){
    try {
        //开启事务
        $db::startTrans();
        //用户信息
        $user = null;
        $tc = null;
        $log = null;
        foreach ($data as $val) {
            $user[] = 'update ' . $prefix . 'user set credit2 = credit2+' . $val['price_d'] . ' where id = ' . $val['uid'];
            $log[] = [
                'username'   => $val['username'],
                'type'       => 'credit2',
                'project'    => 'tcreturn',
                'num'        => $val['price_d'],
                'remark'     => '算力套餐: [' . $tcinfo[$val['tcid']]['name_cn'] . ']到期返还本金，增加' . $val['price_d'] . config('site.credit2_text'),
                'remark_en'  => 'The arithmetic package [' . $tcinfo[$val['tcid']]['name_en'] . '] will return the principal at maturity and increase by ' . $val['price_d'] . config('site.credit2_text'),
                'createtime' => time(),
                'updatetime' => time()
            ];
            $tc[] = 'update ' . $prefix . 'tc_order set status = 1 where id = ' . $val['id'];
        }

        //批量处理
        if ($user) {
            db()->batchQuery($user);
            $user = null;
        }
        if ($log) {
            db('cc_detail_log')->insertAll($log);
            $log = null;
        }
        if ($tc) {
            db()->batchQuery($tc);
            $tc = null;
        }
        //提交事务
        $db::commit();
        $data = db('tc_order')->where('duetime','<=',time())->where('status',0)->where('days_d',0)->field('id,uid,username,tcid,price_d')->limit(0,1000)->select();
    } catch (\Exception $e) {
        //事务回滚
        $db::rollback();
        //记录日志
        plog('套餐到期返还本金',$e->getMessage());
        //跳出循环
        break;
    }
}
echo '执行结束时间：'.date('Y-m-d H:i:s')."\r\n";